package cn.wolfcode.web.controller;


import cn.wolfcode.anno.RequiredPermission;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.domain.LoginException;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.TableInfo;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.*;

@Controller
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private ApplicationContext ctx;

    @RequestMapping("/list")
    public String list(QueryObject qo, Model model){
//        int a = 1/ 0; // TODO 定义异常
/*        // 使用 bootstrap 框架后不需要查询数据
        PageInfo<Permission> pageInfo = permissionService.query(qo);
        model.addAttribute("pageInfo",pageInfo);*/

        return "permission/list";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Permission permission){

        if (permission.getId() == null){
            // 新增
            permissionService.insert(permission);
            return new JsonResult(true, "ok");
        }else {
            // 编辑
            permissionService.update(permission);
            return new JsonResult(true, "ok");
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult deleteById(Long id){
        permissionService.delete(id);
        return new JsonResult(true, "ok");
    }

    /**
     *  bootstrap 框架请求
     */
    @RequestMapping("/listPage")
    @ResponseBody
    public TableInfo listPage(QueryObject qo){
        PageInfo<Permission> pageInfo = permissionService.query(qo);
        return new TableInfo(pageInfo.getTotal(), pageInfo.getList());
    }

    // Excel 导出
    @RequestMapping("/export")
    public void export(HttpServletResponse resp) throws IOException {
        // 1 设置下载头
        resp.setHeader("Content-disposition","attachment;filename=permissionData.xlsx");
        Workbook workbook = permissionService.export();
        workbook.write(resp.getOutputStream());
    }

    // Excel 导入
    @RequestMapping("/import")
    @ResponseBody
    public JsonResult importExcel(MultipartFile file) throws IOException {
        try {
            InputStream inputStream = file.getInputStream();
            Workbook workbook = new XSSFWorkbook(inputStream);
            permissionService.importExcel(workbook);
        } catch (RuntimeException e) {
            return new JsonResult(false, e.getMessage());
        }catch (Exception e){ //
            return new JsonResult(false, "请传入Excel文件夹格式");
        }
      return new JsonResult(true, "导入成功");
    }


    @RequestMapping("/noPermission")
    public String noPermission(){
        return "common/nopermission";
    }



    //=================业务代码抽到业务层==============
    @RequestMapping("/load")
    @ResponseBody
    public JsonResult load(){
        // 查询数据库所有的权限
        List<Permission> allPermissions = permissionService.selectAll();
        // ===去重1 == 使用 set 具有去重 (去除获取方法注解相同的重复) =====
        Set<Permission> permissionList = new HashSet<>();
        // 获取容器所有的控制器对象
        Map<String, Object> beanMap = ctx.getBeansWithAnnotation(Controller.class);
        // 抽离业务层代码放到业务层

        Collection<Object> controllerObjs = beanMap.values();
        for (Object controllerObj : controllerObjs) {
            // 遍历控制器对象获取字节码对象
            Class claz = controllerObj.getClass();
            // 获取每个控制器类中处理方法
            Method[] methods = claz.getDeclaredMethods();
            for (Method method : methods) {
                // 遍历处理方法：获取方法上自定义的注解
                RequiredPermission anno = method.getAnnotation(RequiredPermission.class);
                if (anno != null){  // 贴了注解
                    String name = anno.name();
                    String expression = anno.expression();
                    Permission permission = new Permission(null,name, expression);

                    // == 去重2 == 加入判断，看数据库中有没有该权限，没有才set中添加 （去除重复点击加载按钮时的重复）====
                    if (!allPermissions.contains(permission)){
                        permissionList.add(permission);
                    }
                }
            }
        }
        System.out.println(permissionList);
        // ==== 批量保存 到数据库中 =====
        if (permissionList.size() > 0) {
            permissionService.savePermissions(permissionList);
        }
        return new JsonResult(true, "成功");
    }


}
